package order

import (
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/controllers/login"
	"OnlineRetailers/models/User"
	error2 "OnlineRetailers/models/errorDeal"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type DeleteOrder struct {
	beego.Controller
}

func (c *DeleteOrder) DeleteOrder() {

	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()
	var addr = "/Order/DeleteOrder"
	var openid string
	//res := resMes.GetAdminUser{}
	//user := []*Admin.User{}
	log := &error2.Log{}
	mes := &error2.Mes{}
	order := &User.Order{}
	//orderCart:=[]*User.OrderCart{}
	var err error
	o := orm.NewOrm()
	begin, err := c.GetInt("begin", -1)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	order.OrderId = c.GetString("id")

	if begin == -1 {

		err = session2.CheckSession(c.Ctx.Request.Header["Session"], 2)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	} else {
		err, openid = login.CheckOpenid(c.Ctx.Request.Header["Openid"])
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}

		err = OrderCheck(*order, openid, 0)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	}

	//fmt.Println(key)

	orders := []*struct {
		OrderCartId string
	}{}

	sql := "select * from `order_order_carts` where order_id =?"

	_, err = o.Raw(sql, order.OrderId).QueryRows(&orders)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	fmt.Println(orders)
	sql = "delete from `order_order_carts` where order_id =?"
	_, err = o.Raw(sql, order.OrderId).Exec()
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	for _, orderCartTemp := range orders {
		fmt.Println(orderCartTemp)
		sql = "delete from `order_cart` where order_cart_cart_id =?"
		_, err = o.Raw(sql, orderCartTemp.OrderCartId).Exec()
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	}

	_, err = o.Delete(order)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	mes.Mes = "success"
	mes.Code = "200"
	c.Data["json"] = mes
}

func OrderCheck(order User.Order, openId string, state int) (err error) {

	//fmt.Println(order)
	o := orm.NewOrm()
	sql := "select `order_id` ,`state`  from `order` where order_id=? and user_id=?"

	err = o.Raw(sql, order.OrderId, openId).QueryRow(&order)
	fmt.Println()
	if err != nil {
		return
	} else if (state == 2 && order.State == 1) || state == 6 {

		err = fmt.Errorf("无权限")
		return
	} else if state == order.State {

		fmt.Println(state, order.State)
		err = fmt.Errorf("无效操作")
		return
	}
	return
}
